#include <iostream>
#include <functional>

// 链表节点
template<typename T>
class Node {
public:
    Node(T data) : data_(data), next_(nullptr) {}
    T data() const { return data_; }
    void setNext(Node<T>* next) { next_ = next; }
    Node<T>* next() const { return next_; }

private:
    T data_;
    Node<T>* next_;
};

// 泛型链表类
template<typename T>
class GenericList {
public:
    GenericList() : head_(nullptr), tail_(nullptr) {}
    ~GenericList() {
        while (head_) {
            Node<T>* temp = head_;
            head_ = head_->next();
            delete temp;
        }
    }
    void Add(T data) {
        Node<T>* newNode = new Node<T>(data);
        if (!tail_) {
            head_ = tail_ = newNode;
        } else {
            tail_->setNext(newNode);
            tail_ = newNode;
        }
    }
    Node<T>* Head() const { return head_; }

    // 添加ForEach方法
    void ForEach(std::function<void(T)> action) const {
        for (Node<T>* node = head_; node; node = node->next()) {
            action(node->data());
        }
    }

private:
    Node<T>* head_;
    Node<T>* tail_;
};

int main() {
    GenericList<int> intList;
    for (int x = 0; x < 10; x++) {
        intList.Add(x);
    }

    // 使用lambda表达式打印链表元素
    intList.ForEach([](int data) {
        std::cout << data << std::endl;
    });

    // 使用lambda表达式求链表元素的最大值、最小值和求和
    int max = INT_MIN, min = INT_MAX, sum = 0;
    intList.ForEach([&max, &min, &sum](int data) {
        if (data > max) max = data;
        if (data < min) min = data;
        sum += data;
    });

    std::cout << "链表元素最大值: " << max << std::endl;
    std::cout << "链表元素最小值: " << min << std::endl;
    std::cout << "链表元素之和: " << sum << std::endl;

    return 0;
}
